using System.Collections.Generic;
using System.Text;
using FlashPay.EF.Models;
using FlashPay.Entity;
using FlashPay.Entity.Parameter;
using FlashPay.Service.Interface;
using FlashPay.DAO.Interface;
using System;
using FlashPay.Entity.Response.CardMerchant;
using FlashPay.Entity.Enum;
using Newtonsoft.Json;
using FlashPay.Util;
using System.Linq;

namespace FlashPay.Service.Impl
{
    /// <summary>
    /// 卡商业务接口实现
    /// </summary>
    public class CardMerchantServiceImpl : CardMerchantService
    {
        /// <summary>
        /// 卡商数据接口
        /// </summary>
        private readonly CardMerchantDao cardMerchantDAO;

        /// <summary>
        /// 日志权限数据接口
        /// </summary>
        private readonly LogDao logDao;

        /// <summary>
        /// 公司数据接口
        /// </summary>
        private readonly CompanyDao _companyDao;

        /// <summary>
        /// 日志模型
        /// </summary>
        private readonly LogRecord logRecord;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="cardMerchantDAO">卡商数据接口</param>
        /// <param name="logDao">日志权限数据接口</param>
        /// <param name="companyDao">公司数据接口</param>
        /// <param name="logRecord">日志模型</param>
        public CardMerchantServiceImpl(CardMerchantDao cardMerchantDAO, LogDao logDao, CompanyDao companyDao, LogRecord logRecord)
        {
            this.cardMerchantDAO = cardMerchantDAO;
            this.logDao = logDao;
            this.logRecord = logRecord;
            this._companyDao = companyDao;
        }

        /// <summary>
        /// 根据编号获取卡商
        /// </summary>
        /// <param name="Cmid">编号</param>
        /// <returns>JResult<CardMerchant></returns>
        public JResult<CardMerchant> GetCardMerchant(int Cmid)
        {
            using (cardMerchantDAO)
            {
                JResult<CardMerchant> result = new JResult<CardMerchant>();
                var resultDAO = cardMerchantDAO.Get(Cmid);
                result.Success = true;
                result.Data = resultDAO;
                return result;
            }
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="CardMerchant">新增对象</param>
        /// <returns>JResult</returns>
        public JResult AddCardMerchant(CardMerchant model)
        {
            JResult result = new JResult();
            try
            {
                using (cardMerchantDAO)
                {
                    bool isExist = false;
                    var resultDAO = cardMerchantDAO.Add(model,out isExist);
                    result.Success = resultDAO;

                    //日志
                    logRecord.LogType = LogRecordLogType.CardMerchant_Add.GetHashCode();
                    logRecord.CreateDate = DateTime.Now;
                    logRecord.LogLevel = resultDAO ? (sbyte)LogLevel.Success.GetHashCode():(sbyte)LogLevel.Failure.GetHashCode();
                    logRecord.LogRemark = resultDAO ? "卡商添加成功" : (isExist? "卡商已经存在" : "卡商添加失败");
                    logRecord.RequestData = JsonConvert.SerializeObject(model);
                    logDao.Insert(logRecord);
                    if(isExist)
                    {
                        result.ErrorMessage = "该卡商已经存在！";
                    }
                    else
                    {
                        if (resultDAO)
                        {
                            result.SuccessMessage = "新增成功！";                          
                        }
                        else
                        {
                            result.ErrorMessage = "新增失败！";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                try
                {
                    //日志
                    logRecord.LogType = LogRecordLogType.CardMerchant_Add.GetHashCode();
                    logRecord.CreateDate = DateTime.Now;
                    logRecord.LogLevel = (sbyte)LogLevel.Error.GetHashCode();
                    logRecord.LogRemark = string.Format("卡商添加失败：{0}", ex.Message);
                    logRecord.RequestData = JsonConvert.SerializeObject(model);
                    logDao.Insert(logRecord);

                    //result.ErrorMessage = ex.Message;
                    result.ErrorMessage = "服务器发生异常!";
                }
                catch(Exception)
                {
                    //result.ErrorMessage = e.Message;
                    result.ErrorMessage = "服务器发生异常!";
                }
            }
            return result;

        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="CardMerchant">修改对象</param>
        /// <returns>JResult</returns>
        public JResult UpdateCardMerchant(CardMerchant model)
        {
            JResult result = new JResult();
            try
            {
                using (cardMerchantDAO)
                {
                    var resultDAO = cardMerchantDAO.Update(model);
                    result.Success = resultDAO;

                    logRecord.LogType = LogRecordLogType.CardMerchant_Update.GetHashCode();
                    logRecord.CreateDate = DateTime.Now;
                    logRecord.LogLevel = resultDAO ? (sbyte)LogLevel.Success.GetHashCode() : (sbyte)LogLevel.Failure.GetHashCode();
                    logRecord.LogRemark = resultDAO ? string.Format("卡商修改成功,卡商编号：{0}", model.Cmid) : string.Format("卡商修改失败,卡商编号：{0}", model.Cmid);
                    logRecord.RequestData = JsonConvert.SerializeObject(model);
                    logDao.Insert(logRecord);
                    if (!resultDAO)
                    {
                        result.ErrorMessage = "修改失败！";
                    }
                    else
                    {
                        result.SuccessMessage = "修改成功！";
                    }

                }
            }
            catch (Exception ex)
            {
                try
                {
                    //日志
                    logRecord.LogType = LogRecordLogType.CardMerchant_Update.GetHashCode();
                    logRecord.CreateDate = DateTime.Now;
                    logRecord.LogLevel = (sbyte)LogLevel.Error.GetHashCode();
                    logRecord.LogRemark = string.Format("卡商修改失败：{0}", ex.Message);
                    logRecord.RequestData = JsonConvert.SerializeObject(model);
                    logDao.Insert(logRecord);

                    //result.ErrorMessage = ex.Message;
                    result.ErrorMessage = "服务器发生异常!";
                }
                catch (Exception e)
                {
                    //result.ErrorMessage = e.Message;
                    result.ErrorMessage = "服务器发生异常!";
                }
            }
            return result;

        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="Cmid">编号</param>
        /// <returns>JResult</returns>
        public JResult DeleteCardMerchant(int Cmid)
        {
            JResult result = new JResult();
            try
            {
                using (cardMerchantDAO)
                {
                    bool isUse = false;
                    var resultDAO = cardMerchantDAO.Delete(Cmid,out isUse);
                    result.Success = resultDAO;

                    logRecord.LogType = LogRecordLogType.CardMerchant_Delete.GetHashCode();
                    logRecord.CreateDate = DateTime.Now;
                    logRecord.LogLevel = resultDAO ? (sbyte)LogLevel.Success.GetHashCode() : (sbyte)LogLevel.Failure.GetHashCode();
                    logRecord.LogRemark = resultDAO ? string.Format("卡商删除成功,卡商编号：{0}", Cmid) : (isUse ? string.Format("卡商正在使用,卡商编号：{0}", Cmid) : string.Format("卡商删除失败,卡商编号：{0}", Cmid));
                    logRecord.RequestData = "{\"Cmid\":" + Cmid + "}";
                    logDao.Insert(logRecord);
                    if(isUse)
                    {
                        result.ErrorMessage = "卡商正在使用！";
                    }
                    else
                    {
                        if (!result.Success)
                        {
                            result.ErrorMessage = "删除失败！";
                        }
                        else
                        {
                            result.SuccessMessage = "删除成功！";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                try
                {
                    //日志
                    logRecord.LogType = LogRecordLogType.CardMerchant_Delete.GetHashCode();
                    logRecord.CreateDate = DateTime.Now;
                    logRecord.LogLevel = (sbyte)LogLevel.Error.GetHashCode();
                    logRecord.LogRemark = string.Format("卡商删除失败：{0}", ex.Message);
                    logRecord.RequestData = "{\"Cmid\":" + Cmid + "}";
                    logDao.Insert(logRecord);

                    //result.ErrorMessage = ex.Message;
                    result.ErrorMessage = "服务器发生异常!";
                }
                catch (Exception e)
                {
                    //result.ErrorMessage = e.Message;
                    result.ErrorMessage = "服务器发生异常!";
                }
            }
            return result;
        }

        /// <summary>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              
        /// 获取所有卡商记录
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>List<CardMerchant></returns>
        public List<CardMerchant> GetList(CardMerchantQuery query)
        {
            return cardMerchantDAO.GetList(query);
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<CardMerchant></returns>
        public PagedList<CardMerchantResponse> CardMerchantPage(CardMerchantQuery query)
        {
            #region 获取当前公司及子公司编号
            //参数赋值
            var companyRequest = new EF.Models.Company()
            {
                CompanyId = query.CompanyId.Value,
                CompanyPid = -1,
                CompanyStatus = 1
            };

            var companyQueryResult = new BaseModel<List<EF.Models.Company>>();
            //查询
            _companyDao.Get(companyQueryResult, companyRequest, 2);
            if (companyQueryResult != null && companyQueryResult.Success)
            {
                var companyIds = new List<int>();

                if (companyQueryResult.Result != null && companyQueryResult.Result.Count > 0)
                {
                    companyQueryResult.Result.ForEach(item => {
                        companyIds.Add(item.CompanyId);
                    });
                }

                if (companyIds != null && companyIds.Any())
                {
                    query.CompanyIds = companyIds;
                }
            }
            #endregion

            using (cardMerchantDAO)
            {
                var result = cardMerchantDAO.GetPager(query);
                return result;
            }
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>JResult<List<CardMerchant>></returns>
        public JResult<List<CardMerchant>> CardMerchantList(CardMerchantQuery model)
        {
            using (cardMerchantDAO)
            {
                JResult<List<CardMerchant>> result = new JResult<List<CardMerchant>>();
                result.Data = cardMerchantDAO.GetList(model);
                result.Success = true;
                return result;
            }
        }

        /// <summary>
        /// 通过条件获取卡商信息
        /// </summary>
        /// <param name="SearchValue">搜索值</param>
        /// <param name="SearchType">值类型</param>
        /// <returns>List<CardMerchant></returns>
        public JResult<List<CardMerchantResponse>> SearchCardMerchant(CardMerchantQuery query)
        {
            using (cardMerchantDAO)
            {
                #region 获取当前公司及子公司编号
                //参数赋值
                var companyRequest = new EF.Models.Company()
                {
                    CompanyId = query.CompanyId.Value,
                    CompanyPid = -1,
                    CompanyStatus = 1
                };

                var companyQueryResult = new BaseModel<List<EF.Models.Company>>();
                //查询
                _companyDao.Get(companyQueryResult, companyRequest, 2);
                if (companyQueryResult != null && companyQueryResult.Success)
                {
                    var companyIds = new List<int>();

                    companyQueryResult.Result.ForEach(item => {
                        companyIds.Add(item.CompanyId);
                    });

                    if (companyIds != null && companyIds.Any()) {
                        query.CompanyIds = companyIds;
                    }
                }
                #endregion


                var list = cardMerchantDAO.SearchCardMerchant(query);

                return new JResult<List<CardMerchantResponse>>() {
                    Success = true,
                    Data = list
                };
            }
        }
    }
}
